/** 
 * @CopyRight (c) 2012-2012
 * @Project <jtao>
 * @JDK_Version_Used:<JDK1.6>
 * @Description:<JSON字符串工具>
 * @Title: JsonTools.java
 * @Author: <何俊>
 * @Author_of_Contact <E:azj1001@sina.com T:18651831939>
 * @Date 2012-11-4 下午5:39:25
 * @Modified_By: <修改人>
 * @Modified_of_Contact <修改人联系方式>
 * @Modified_Date <修改日期时间>
 * @Why & What is modified <修改原因描述>
 * @Version v1.00
 */
package com.e.buy.tools;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;

import cn.commons.ICommons;
import cn.commons.dbclient.exception.AzjDbClientException;

import com.e.buy.bean.Dmlx;

/**
 * @Description:(JSON字符串工具)
 * @author <何俊>
 * @date 2012-11-4 下午5:39:25
 * @version v1.0
 * @Other :@see #Files
 */
final public class ToolsBox {

	// 自身日志监听
	/** 日志记录 */
	private static final Logger log4j = Logger.getLogger(ToolsBox.class);
	// 线程安全锁
	private static final Object lockObj = new Object();

	// 对象实例
	private static ToolsBox instance = null;

	@Resource
	protected ICommons service = null;

	// 服务器代码缓存
	private Map<String, List<Dmlx>> dmlxs = null;
	private String flg = "dm=";
	private boolean initOk = false;

	private void init() {
		log4j.info("服务器DMLX缓存数据加载...!!");
		dmlxs = new HashMap<String, List<Dmlx>>();
		String sql;
		try {
			sql = service.getSql("sql", "commons.cache.dmlx");
			@SuppressWarnings("unchecked")
			List<Dmlx> ls = (List<Dmlx>) service.queryForList(sql, Dmlx.class);
			if (ls != null && !ls.isEmpty()) {
				String key = "";
				for (Dmlx d : ls) {
					key = flg + d.getDm();
					if (dmlxs.containsKey(key)) {
						dmlxs.get(key).add(d);
					} else {
						List<Dmlx> ds = new ArrayList<Dmlx>();
						ds.add(d);
						dmlxs.put(key, ds);
					}
				}
			}
			initOk = true;
		} catch (AzjDbClientException e) {
			initOk = false;
			dmlxs = new HashMap<String, List<Dmlx>>();
			log4j.error("服务器DMLX缓存数据加载失败...!!" + e);
		}
	}

	public static ToolsBox getInstance() {
		if (null == instance) {
			synchronized (lockObj) {
				if (null == instance) {
					instance = new ToolsBox();
					log4j.info("load JsonTools complete!");
				}
			}
		}
		return instance;
	}

	/**
	 * 把json字符串转化成指定对象类型
	 * 
	 * @title: jsonstr2Object
	 * @param jsonStr
	 * @param objClass
	 * @return Object 返回类型
	 * @throws
	 */
	public Object jsonstr2Object(String jsonStr, Class<?> objClass) {
		JSONObject json = JSONObject.fromObject(jsonStr);
		Object obj = JSONObject.toBean(json, objClass);
		return obj;
	}

	/**
	 * 将jsonArray字符串，转换成List<?> 对象
	 * 
	 * @title: jsonArraystr2List
	 * @param jsonStr
	 * @param c : 对象的类型
	 * @return List<?> 返回类型
	 * @throws
	 */
	@SuppressWarnings("rawtypes")
	public List<?> jsonArraystr2List(String jsonStr, Class<?> c) {
		JSONArray array = JSONArray.fromObject(jsonStr);
		List<?> ls = new ArrayList();
		ls = (List<?>) (JSONArray.toCollection(array, c));
		return ls;
	}

	/**
	 * 把传入的对象直接转换成Json格式字符串
	 * 
	 * @title: transformObjToJson
	 * @param obj
	 * @param excludes : 需要拒绝的 字段 名称,多值或数组
	 * @return JSONObject 返回类型
	 * @throws
	 */
	public String obj2Jsonstr(Object obj, String... excludes) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setExcludes(excludes);
		JSONObject json = JSONObject.fromObject(obj, jsonConfig);
		return json.toString();
	}

	/**
	 * 把传入的List对象转换成JsonArray格式字符串
	 * 
	 * @title: transformListToJsonArrayStr
	 * @param ls
	 * @param excludes : 需要拒绝的 字段 名称,多值或数组
	 * @return String 返回类型
	 * @throws
	 */
	public String list2JsonArrayStr(List<?> ls, String... excludes) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setExcludes(excludes);
		JSONArray array = JSONArray.fromObject(ls, jsonConfig);
		return array.toString();
	}

	/**
	 * 将toolbar集合转换成页面显示的带分隔符的toolbar
	 * 
	 * @title: list2ToolbarStr
	 * @param ls
	 * @param excludes
	 * @return String 返回类型
	 * @throws
	 */
	public String toolbarStr(List<?> ls, String... excludes) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setExcludes(excludes);
		JSONArray array = JSONArray.fromObject(ls, jsonConfig);
		int size = array.size();
		int index = -1;
		int start = 0;
		while (start < size) {
			index = index + 2;
			array.add(index, "-");
			start++;
		}
		return array.toString();
	}

	/**
	 * 将字符串转化成GBK格式
	 * 
	 * @title: encoding2GBK
	 * @param str
	 * @return String 返回类型
	 * @throws
	 */
	public String encoding2GBK(String str) throws UnsupportedEncodingException {
		String gbk = null;
		if (null == str || str.trim().length() == 0) {
			return str;
		}
		try {
			gbk = new String(str.getBytes("iso-8859-1"), "GBK");
		} catch (UnsupportedEncodingException e) {
			gbk = str;
			throw e;
		}
		return gbk;
	}

	/**
	 * 获取java的UUID
	 * @title: getJavaUUID
	 * @return String 返回类型
	 * @throws
	 */
	public String getJavaUUID() {
		return UUID.randomUUID().toString();
	}

	/**
	 * @Description:<获取随机数字：a-zA-Z0-9_&^! >
	 * @title: getRandomID
	 * @param length
	 * @return
	 * @return String 返回类型
	 * @throws
	 */
	public String getRandomID(int length) {
		StringBuilder str = new StringBuilder();
		int v = 0;
		Random random = new Random();
		while (length > 0) {
			v = random.nextInt(125);
			// 小写字符,大写字符
			if ((v >= 65 && v <= 90) || (v >= 97 && v <= 122)) {
				str.append((char) v);
			} else if (v >= 0 && v <= 9) {
				str.append(v);
			} else if (v == 33 || v == 37 || v == 94 || v == 38 || v == 95) {
				str.append((char) v);
			} else {
				length++;
			}
			length--;
		}
		return new String(str.toString());
	}

	/**
	 * @Description:<将传入的时间字符串转换成当前Mysql的时间毫秒数。传入的为空，则去当前时间>
	 * @title: getMysqlTimeMsec
	 * @param dateStr
	 * @throws ParseException
	 * @return long 返回类型
	 * @throws
	 */
	public long getMysqlTimeMsec(String dateStr) throws ParseException {
		Date d = null;
		if (null == dateStr || dateStr.isEmpty()) {
			d = new Date();
		} else {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			d = df.parse(dateStr);
		}
		return d.getTime() / 1000;
	}

	/**
	 * @Description:<格式化Java.util.Date 为字符串>
	 * @title: dateFormat
	 * @param date
	 * @param formart
	 * @return String 返回类型
	 * @throws
	 */
	public String dateFormat(Date date,String formart) {
		String time = null;
		if(date == null) {
			return time;
		}
		if(formart == null) {
			formart = "yyyy-MM-dd HH:mm:ss";
		}
		try{
			SimpleDateFormat df = new SimpleDateFormat(formart);
			time = df.format(date);
		} catch (Exception e) {
			time = null;
		}
		return time;
	}
	/**
	 * 根据Mysql数据库的时间毫秒数，返回
	 * @Description:<函数描述>
	 * @title: getJavaTime
	 * @param msec
	 * @return String 返回类型
	 * @throws
	 */
	public String getJavaTime(long msec) {
		long l = msec * 1000;
		Date d = new Date(l);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(d);
	}

	/**
	 * @Description:<获取缓存代码值>
	 * @title: dmlxStr
	 * @param dm : 代码值
	 * @param online : 是否在线获取
	 * @return String 返回类型
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public String dmlxStr(int dm, boolean online) {
		List<Dmlx> ls = new ArrayList<Dmlx>();
		// 安全检查
		if (null == dmlxs) {
			init();
		}
		
		if(!initOk) {
			online = true;
		}
		
		if(online) {
			String sql;
			try {
				sql = service.getSql("sql", "commons.cache.dmlx.bydm");
				ls = (List<Dmlx>) service.queryForList(sql, Dmlx.class,dm);
				dmlxs.remove(flg + dm);
				dmlxs.put(flg + dm, ls);
			} catch (AzjDbClientException e) {
				ls = new ArrayList<Dmlx>();
				log4j.error("Online Find dm=" + dm + " occur Exception...!! " + e);
			}
		} else {
			ls = dmlxs.get(flg + dm);
		}
		return list2JsonArrayStr(ls);
	}

	public void setService(ICommons service) {
		this.service = service;
	}

}
